package adapteurMediaStore;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AlbumColumns;
import android.util.Log;

import com.insta.playdroid.AlbumActivity2;
import com.insta.playdroid.metier.domain.Album;

public class AdapteurAlbumMediaStore implements IAdapteurMediaStore<Album> {

	private Context context;

	public AdapteurAlbumMediaStore(Context context) {
		this.context = context;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see adapteurMediaStore.IAdapteurMediaStore#collectAllValuesFromDB()
	 */
	@Override
	public List<Album> collectAllValuesFromDB() {

		List<Album> albums = new ArrayList<Album>();
		int id;
		String albumTitre;
		String albumArt;

		// the cursor we will use to iterate over the db results
		Cursor cursor = null;

		// the list of columns our search relates to
		final String[] projection = new String[] { MediaStore.Audio.Albums._ID,
				MediaStore.Audio.AlbumColumns.ALBUM,
				MediaStore.Audio.AlbumColumns.ALBUM_ART };

		// how we want to sort our results
		final String sortOrder = AlbumColumns.ALBUM + " COLLATE LOCALIZED ASC";

		try {
			// the uri of the table that we want to query
			Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;

			// launch the query
			cursor = context.getContentResolver().query(uri, projection, null,
					null, sortOrder);

			if (cursor != null) {
				albums = new ArrayList<Album>(cursor.getCount());

				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {
					// get the 1st parameter in our query string
					// (AlbumColumns.ALBUM)

					id = cursor.getInt(0);
					albumTitre = cursor.getString(1);
					albumArt = cursor.getString(2);
					albums.add(new Album(id, albumTitre, albumArt));

					cursor.moveToNext();

				}
			}
		} catch (Exception ex) {
			Log.e(AlbumActivity2.class.getName(),
					"Error querying music db for all albums");
		} finally {
			if (cursor != null) {
				cursor.close();
			}

		}
		return albums;
	}

}
